package site.eblog.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import site.eblog.listener.FileUploadUtil;

import site.eblog.entity.RegexUtil;

import site.eblog.entity.User;
import site.eblog.security.MyMD5;
import site.eblog.service.UserService;

@Controller
public class UserController {
	
	@Autowired UserService userService;
	
	@RequestMapping("register.do")
	@ResponseBody
	public Map<String,Object> register(@RequestBody User user){
		Map<String,Object> resO = new HashMap<String, Object>();
		int res = 0;
		int userRoleRes = 0;
		String rerro;
		resO.put("res", res);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		user.setRegisterTime(df.format(new Date()));// new Date()为获取当前系统时间
		if(user.getUserPic() == null){
			user.setUserPic("assets/manager/img/logo.png");
		}
		if(user.getCoverPic() == null){
			user.setCoverPic("assets/manager/img/profile_big.jpg");
		}
		
		String userName = user.getName();
		String password = user.getPassword();
		String Phone = user.getPhone();
		String Email = user.getEmail();
		boolean isName = RegexUtil.isName(userName);
		boolean isPwd = RegexUtil.isPwd(password);
		boolean isPhone = RegexUtil.isMobile(Phone);
		boolean isEmail = RegexUtil.isEmail(Email);
		if(!isName){
			rerro = "用户名格式不正确,要求是5-16位数字，字母组合！";
			resO.put("resMsg", rerro);
		}
		else if(!isPwd){
			rerro = "密码格式不正确，要求是6-18位数字字母组合！";
			resO.put("resMsg", rerro);
		}
		else if(Phone != null && Phone != "" && !isPhone){
			rerro = "手机格式不正确！";
			resO.put("resMsg", rerro);
		}
		else if(Email != null && Email != "" && !isEmail){
			rerro = "Email格式不正确！";
			resO.put("resMsg", rerro);
		}
		else{
			String DM5PassWord = MyMD5.MD5(password);
			user.setPassword(DM5PassWord);
			res = userService.insertUser(user);
			if(res == 1){
				User newUser = userService.findByName(userName);
				userRoleRes = userService.insertUserRole(newUser);
				if(userRoleRes == 1){
					resO.put("newUserRole", userRoleRes);
					resO.put("res", res);
				}
			}else{
				resO.put("resMsg", "注册失败。");
			}
		}
		return resO;
	}
	//注册时检查name是否已存在
	@RequestMapping("checkByName")
	@ResponseBody
	public int checkByName(HttpServletRequest request){
		int res = 1;
		String name = request.getParameter("name");
		User user = userService.findByName(name);
		if(user == null){
			res = 0;
		}
		return res;
	}
	
	//修改userinfo
	@RequestMapping("edituserinfo")
	@ResponseBody
	public Map<String,Object> editUserInfo(@RequestBody User user){
		Subject currentUser = SecurityUtils.getSubject();
		String sessionName  = (String)currentUser.getPrincipal();
		user.setName(sessionName);
		Map<String,Object> resMsg = new HashMap<>();
		String rerro;
		int res = 0;
		String passWord = user.getPassword();
		String Phone = user.getPhone();
		String Email = user.getEmail();
		String bornD = user.getBornD();
		int bornDYear = Integer.parseInt(bornD.split("\\-")[0]);
		Calendar now = Calendar.getInstance(); 
		int nowYear = now.get(Calendar.YEAR);
		user.setAge(nowYear - bornDYear);
		boolean isPW = RegexUtil.isPwd(passWord);
		boolean isPhone = RegexUtil.isMobile(Phone);
		boolean isEmail = RegexUtil.isEmail(Email);
		if(passWord != null && passWord != "" && !isPW){
			rerro = "密码格式不正确！";
			resMsg.put("resMsg", rerro);
		}
		else if(Phone != null && Phone != "" && !isPhone){
			rerro = "手机格式不正确！";
			resMsg.put("resMsg", rerro);
		}
		else if(Email != null && Email != "" && !isEmail){
			rerro = "Email格式不正确！";
			resMsg.put("resMsg", rerro);
		}else{
			if(passWord != null && passWord != ""){
				String DM5PassWord = MyMD5.MD5(passWord);
				user.setPassword(DM5PassWord);
			}
			res = userService.editUserInfo(user);
		}
		resMsg.put("res", res);
		return resMsg;
	}
	
	//修改密码
	@RequestMapping("edituserPW")
	@ResponseBody
	public Map<String,Object> editUserPW(@RequestBody User user){
		Subject currentUser = SecurityUtils.getSubject();
		String sessionName  = (String)currentUser.getPrincipal();
		user.setName(sessionName);
		Map<String,Object> resMsg = new HashMap<>();
		String rerro;
		int res = 0;
		String passWord = user.getPassword();
		boolean isPW = RegexUtil.isPwd(passWord);
		if(passWord != null && passWord != "" && !isPW){
			rerro = "密码格式不正确！";
			resMsg.put("resMsg", rerro);
		}
		else{
			String DM5PassWord = MyMD5.MD5(passWord);
			user.setPassword(DM5PassWord);
			res = userService.editUserInfo(user);
		}
		resMsg.put("res", res);
		return resMsg;
	}
	
	//修改图片
	@RequestMapping("editPic")
	@ResponseBody
	public Map<String,Object> editPic(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") CommonsMultipartFile file) throws IOException {
		Map<String,Object> resMsg = new HashMap<>();
		User user = new User();
		String picPath = "";
		String msg = "";
		long setFileSizeMax = 2097152L;//定义最大文件为2M，字节形式
		long fileSize = file.getSize();//获取文件大小，字节形式
		Subject currentUser = SecurityUtils.getSubject();
		String userName = currentUser.getPrincipal().toString();
		user.setName(userName);
		
		response.setContentType("text/html");
		response.setCharacterEncoding("GBK");
		Map<String,String> flag = new HashMap<String, String>();
		
		if(fileSize > setFileSizeMax){
			msg = "文件超过了2M！";
			resMsg.put("res", "0");
			resMsg.put("msg", msg);
		}else{
			if (file.getSize() > 0) {
				//文件上传的位置可以自定义 
				flag = FileUploadUtil.upLoadFile(request,file);			
			}
			if (flag.get("upRes").equals("true")) {
				picPath = flag.get("picPath");
				resMsg.put("picPath", picPath);
				if(flag.get("type").equals("userPic")){
					user.setUserPic(picPath);
				}else{
					user.setCoverPic(picPath);
				}
				int upRes = userService.editUserInfo(user);
				resMsg.put("res", upRes);
			} else {
				resMsg.put("res", "0");
			}
		}
		return resMsg;
	}
	//修改图片
	
	//用户管理getUsers
	@RequestMapping("getUsers")
	@ResponseBody
	public Map<String,Object> getUser(HttpServletRequest request){
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		Map<String,Object> resMap = new HashMap<>();
		List<User> users = new ArrayList<>();
		PageHelper.startPage(page, pageSize);
		users = userService.getUsers();
		PageInfo pageInfo = new PageInfo(users);
		resMap.put("pageInfo", pageInfo);
		return resMap;
		
	}
	//deleteUser
	@RequestMapping("delUser")
	@ResponseBody
	public Map<String,Object> delUser(HttpServletRequest rquest){
		Map<String,Object> resMsg = new HashMap<>();
		int roleRes;
		String userName = rquest.getParameter("userName");
		User user = userService.findByName(userName);
		int userId = user.getId();
		int res = userService.delUser(userName);
		if(res==1){//如果成功del用户，就把user_role对应的role删掉
			roleRes = userService.delUserRole(userId);
		}
		resMsg.put("res", res);
		return resMsg;
	}
	//用户管理
	
	//centerGetUser
	@RequestMapping("centerGetUser")
	@ResponseBody
	public User centerGetUser(){
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		String author = session.getAttribute("centerAuthor").toString();
		User user = userService.findByName(author);
		user.setPassword("");
		user.setAge(0);
		user.setBornD("");
		user.setEmail("");
		user.setPhone("");
		return user;
	}
	//centerGetUser
}
